/*
 * detail		: 发送验证码
 * obj 			: 发送按钮，是一个超链接或者按钮
 * nameobj		: 文本框，要发送验证码的手机号
 * smsType		: 短信类型
 */
function change_code(obj, nameobj, smsType) {
    if ($(obj).attr('disabled')) {
        return;
    }

    var phoneInput = $(nameobj);

    var phone = "";
    if (phoneInput.is("input")) {
        if ("" == phoneInput.val()) {
            $.toast("请输入手机号码");
            return;
        }

        if (!isTelephone(phoneInput.val())) {
            $.toast("请输入正确的手机号");
            return;
        }

        phone = phoneInput.val();
    } else {
        phone = phoneInput.attr("tip");
    }

    // 验证码计时器
    smsTimer(obj, nameobj, smsType);
    
    var requestType = CONFIG_MANAGER.RequstUrl;
    requestType += "v1/sms/"+ smsType +"/" + phone;
    console.log(requestType);
    // 发送验证码
    $.ajax({
        type: "GET",
        url: requestType,
    }).done(function (data) {
        if ("success" == data.retMsg) {
        }
    }).fail(function(data){
    	$.toast(data.responseJSON.Message);
    });
}

/*
 * detail		: 修改样式
 * obj 			: 发送按钮，是一个超链接或者按钮
 * nameobj		: 文本框，要发送验证码的手机号
 * smsType		: 短信类型
 */
function smsTimer(obj, nameobj, smsType) {
    var timecount = CONFIG_MANAGER.senddelay;
    $(obj).attr('disabled', true).addClass("sms-button-disable").text(timecount + "S后重新获取");
    var stopwatch = setInterval(function () {
        timecount = timecount - 1;
        if (timecount == 0) {
            $(obj).attr('disabled', false).removeClass("sms-button-disable").text("重新获取验证码");
            clearInterval(stopwatch);
            return;
        }
        $(obj).text(timecount + "S后重新获取");
    }, 1000);
}

/**
 * 根据内容生成二维码
 * @param {Image} imageOjb_Image对象
 * @param {String} infor_二维码保存的内容
 */
function getBarImage(imageOjb, infor){
	$.ajax({
		type: "GET",
		url: CONFIG_MANAGER.serverUrl + "barcode.php?code=" + infor,
		async: true
	}).done(function(data) {
		$(imageOjb).attr("src", "http://d1.soolife.net/qrcode/" + data + ".jpg");
	});	
}

/**
 * @param {String} content_要复制的内容
 */
function copyToClip(content){
	try{
		if(AGENT_CLIENT.APP){
			if(os.android){
				var Context = plus.android.importClass("android.content.Context");
			    var main = plus.android.runtimeMainActivity();
			    var clip = main.getSystemService(Context.CLIPBOARD_SERVICE);
			    plus.android.invoke(clip,"setText",content);			
			}else if(os.ios){
				var UIPasteboard  = plus.ios.importClass("UIPasteboard");
				var generalPasteboard = UIPasteboard.generalPasteboard();
				generalPasteboard.setValueforPasteboardType(content, "public.utf8-plain-text");
				var value = generalPasteboard.valueForPasteboardType("public.utf8-plain-text");   				
			}else{
				return false
			}
		}else{
			return false;
		}
	}catch(e){
		//TODO handle the exception
		console.log(e);
		return false;
	}
	return true;
}

/**
 * 根据当前订单状态获取可进行的操作
 * @param {URIString} orderStatus :
 * 0-新订单 1-系统确认订单 2-在线支付完成 3-已取消订单 4-已删除订单 5-仓库已接收（商家确认、仓库确认）
 * 6-商品打包中 7-发货中 8-客户已收货 9-正在退款 10-退款成功 11-退款失败
 * @return {Object} operation : 对应操作
 **/
function getOrderOperation(orderStatus,isComment){
  var operation = [];
  switch (orderStatus){  
  	case 0:
  	case 1: 
  	  operation = [{key:"pay",text:"付款"}, {key:"cancel",text:"取消订单"}]; 
  	  break;
  	case 2:
  	case 5:
  	case 6:
  	case 7: 
  	  operation = [{key:"checkDelivery",text:"查看物流"}, {key:"confirmDelivery",text:"确认收货"}]; 
  	  break;
  	case 8:
  	  operation.push({key:"applyApplication",text:"申请售后"});
  	  if("N" == isComment){
  	    operation.push({key:"appraise",text:"评价"});
  	  }
	    break;
  	//case 3: operation = [{key:"delete",text:"删除"}]; break;
  	case 9: 
  	  operation = [{key:"cancelApplication", text:"取消申请"},{key:"finish",text:"完成"}]; 
  	  break;
  	default:
  		break;
  }
  //operation = [{key:"checkDelivery",text:"查看物流"}, {key:"confirmDelivery",text:"确认收货"}]; 
  return operation;
}

/**
 * 订单操作 
 * @param {URIString} ops : 操作类型
 * @param {Object} order : 订单数据
 **/
function operateOrder(order){  
  var requestUrl = CONFIG_MANAGER.RequstUrl;
  var type = "POST";
  var inforMessage = "";
  switch (order.ops){
    case "pay":                 redirect("../shopcart/payCenter.html?mainorderno=" + order.mainorderno);                              		   break; //支付
    case "cancel":              requestUrl += "v1/orders/cancel/" + order.id; type="DELETE"; inforMessage="取消成功";             break; //取消
    case "checkDelivery":       redirect("delivery.html?id=" + order.id);                               												 break; //查看物流
    case "confirmDelivery":     requestUrl += "v1/orders/confirm/" + order.id;               inforMessage="确认成功";           	 break; //确认收货
    case "appraise":            redirect("orderappraise.html?id=" + order.id);                          												 break; //评价订单
    case "applyApplication":    redirect("afterSale.html?id=" + order.id);                              												 break; //申请售后
    case "cancelApplication":   requestUrl += "v1/stockreturn/cancel/{org}/{returnno}"; type="DELETE"; inforMessage="取消成功";   break; //取消申请
    //case "delete":              requestUrl += "v1/stockreturn/delete/{returnno}"; type="DELETE";        break; //删除
    default: break;
  }
  if("" == inforMessage){
  	inforMessage = "操作成功";
  }
  if( requestUrl != CONFIG_MANAGER.RequstUrl ){ 
    console.log(requestUrl);
    var user = getLocalStorage(STORAGE_MANAGER.user);
    $.ajax({
    	type:type,
    	url:requestUrl,
    	headers:{ token:user.token },
    	async:true,
    	beforeSend:function(){ $.showWaiting() }
    }).done(function(data){
    	$.toast(inforMessage);
      if(AGENT_CLIENT.APP){
      	if(order.ops == "cancel"){
      		plus.webview.getWebviewById("../mine/mylife.html").evalJS("reloadPage()");
      	}
      }
    }).always(function(data){
      $.closeWaiting();
    });
  }
}

/**
 * 申请售后的状态 0：新申请 1：处理中 2：已处理 3：取消 4：已结束 11：已生成调拨单 12：调拨完成	
 * @param {Int} status : 状态值
 * @return {String} statusText : 状态描述
 * */
function afterStatusText(status){
	var statusText = '';
	switch (status){
		case 0:
			statusText = '新申请';
			break;
		case 1:
			statusText = '处理中';
			break;
		case 2:
			statusText = '已处理';
			break;
		case 3:
			statusText = '取消';
			break;
		case 4:
			statusText = '已处理';
			break;
		case 5:
			statusText = '未解决(客户确认未解决)';
			break;	
		case 6:
			statusText = '已解决(客户确认已解决)';
			break;			
		case 11:
			statusText = '已生成调拨单';
			break;
		case 12:
			statusText = '调拨完成';
			break;
		default:
			statusText = '未知';
			break;
	}
	return statusText;
}

/**
 * 根据申请售后订单状态显示对应的操作
 * @param {String} status : 状态值
 * @return {Array} operation : 对应的操作
 * */
function getAfterOperation(status){
	var operation = [];
	switch (status){
		//0：新申请 [取消申请]
		case 0:
			operation = [{key:"cancel",text:"取消申请",status:0}];
			break;
		//4：已处理 [已解决]，[未解决]
		case 4:
			operation = [{key:"resolved",text:"已解决",status:1},{key:"unsolved",text:"未解决",status:2}];
			break;
		default:
			break;
	}
	return operation;
}

/**
 * 售后服务操作
 *	@param {String} order_no : 订单编号 
 **/
function afterSaleOperation(order, statusText){
  var requestUrl = CONFIG_MANAGER.RequstUrl + 'v1/orders/after/editstatus/' + order.aftersales_id + "/";
  var type = "POST";
  var inforMessage = "";	
	switch (order.key){
		case 'cancel':
			requestUrl += '0';
			inforMessage = "取消成功";
			break;
		case 'resolved':
			requestUrl += '1';
			inforMessage = "谢谢您的支持";
			break;
		case 'unsolved':
			inforMessage = "请联系客服";
			requestUrl += '2';
			break;
		default:
			break;
	}
	$.ajax({
		type:type,
		url:requestUrl,
		async:true,
		beforeSend:function(){ $.showWaiting(); }
	}).done(function(data){
		$.toast(inforMessage);
		var newStatus = "";
		switch (order.key){
			case "cancel":
				newStatus = "finish";
				break;
			case "resolved":
				newStatus = "finish";
				break;
			case "unsolved":
				newStatus = statusText;
				break;
			default:
				break;
		}
		redirect("aftersaleorders.html?status=" + newStatus);
	}).fail(function(data){
		$.toast(data.responseJSON.Message);
	}).always(function(){
		$.closeWaiting();
	});
}

/**
 * 将二维码图片保存到手机相册
 * @param {String} url : 图片的url
 */
function saveGallery(url) {
    var dtask = plus.downloader.createDownload(url, {}, function (d, status) {
        // 下载完成
        if (status == 200) {
            var filepath = plus.io.convertLocalFileSystemURL(d.filename);
            console.log(filepath);
            plus.gallery.save(filepath);
            plus.nativeUI.toast("保存成功");
            plus.io.resolveLocalFileSystemURL(filepath, function (entry) {
                entry.remove(function (e) { }, function (e) { });
            }, function (e) { });

        } else {
            plus.nativeUI.alert("Download failed: " + status);
        }
    });
    //dtask.addEventListener( "statechanged", onStateChanged, false );
    dtask.start();
}


/**
 * 选择省市区
 * 
 * */
function selectRegion(thisSelect){
    var value = $(thisSelect).val(), id = $(thisSelect).attr("id");
    $.ajax({
        type: "GET",
        url: CONFIG_MANAGER.RequstUrl + "v1/basic/region/child/" + value,
        async: true
    }).done(function (data) {
        var i = 0, html = [];
        while (data[i] && "CN" != data[i].id) {
            html.push("<option value=" + data[i].id + ">" + data[i].name + "</option>");
            i++;
        }
        //市
        if ("province" == id) {
        	//直辖市直接把区选择出来        	
        	if (["CN11","CN31","CN12","CN50"].indexOf(value)>-1) {
	            $("#city").html(html.join(''));
			    $.ajax({
			        type: "GET",
			        url: CONFIG_MANAGER.RequstUrl + "v1/basic/region/child/" + data[0].id,
			        async: true
			    }).done(function(data){
			    	i=0;
			    	html = [];
			    	while (data[i]){
			    		html.push("<option value=" + data[i].id + ">" + data[i].name + "</option>");
			    		i++;
			    	}
			    	$("#country").html(html.join(''));
			    });
        	} else{
	            html.unshift("<option value='0' selected='selected'>选择市</option>");
	            $("#city").html(html.join(''));
	            $("#country").html("<option value='0' selected='selected'>选择区</option>");
        	}
        	
        }
        //区
        else if("city" == id) {
        	var province = $("#province").val();
        	if(["CN11","CN31","CN12","CN50"].indexOf(province) == -1){
        		html.unshift("<option value='0' selected='selected'>选择区</option>");
        	}
            $("#country").html(html.join(''));
        }
    });	
}

/**
 * 获取返现类型
 * @param {Int32Array} type : 类型值
 **/
function getRewardMoneyType(type){
	var value = "";
	switch (type){
		case 1:
			value = "钱包";
			break;
		case 2:
			value = "现金";
			break;			
		default:
			break;
	}
	return value;
}

/**
 * 根据情况返回到上一个页面
 * @param {String} fromurl : 从那里来
 * @param {Boolean} isRefresh ： 是否要刷新
 **/
function backToPreviousPage(fromurl, isRefresh){
	if(fromurl){
		fromurl = "../" + fromurl.replace('|', "/");
		if(AGENT_CLIENT.APP){
	    var homePages = {
	      "../home/main.html": -1,
	      '../home/index.html': 0,
	      '../home/classification.html': 1,
	      '../coin/coinlist.html': 2,
	      '../shopcart/shoppingcart.html': 3,
	      '../mine/mylife.html': 4
	    };
	    //我的页面实时刷新
	    if(/mylife\.html/.test(fromurl) && isRefresh){
	    	plus.webview.getWebviewById("../mine/mylife.html").evalJS("reloadPage()");
	    }
	    console.log('fromurl:'+fromurl);
	    console.log('homePages[fromurl]:'+homePages[fromurl]);	    
	    if (undefined != homePages[fromurl] && homePages[fromurl] != -1) {    	
	      plus.webview.getWebviewById("../home/main.html").evalJS("redirectTab(" + homePages[fromurl] + ")");
	      plus.webview.currentWebview().close();
	    } else {
	      redirect(fromurl, false, "pop-out", function () {
	          plus.webview.currentWebview().close();
	      });
	    }
    }else{
    	redirect(fromurl);
    }
	}else{
		back();
	}
	
}

/**
 * 获取我的收入类型文字
 * @param {int} suorce_type : 收入类型
 * @return {String} source_type_string : 收入类型文字
 * */
function getincomeType(suorce_type){
	var source_type_string = '';
	switch (suorce_type){
		case 8:
		case 9:
			source_type_string = '全民商探';
			break;
		case 10:
			source_type_string = '惠赚钱';
			break;		
		default:
			source_type_string = '其他';
			break;
	}
	return source_type_string;
}
